import 'dart:async';
import 'package:flutter/material.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/services.dart';
import 'chart.dart';
import 'onenet.dart';

void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MQTT',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(title: 'MQTT Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final c1 = TextEditingController();
  final c2 = TextEditingController();
  final c3 = TextEditingController();

  ScrollController scrollController = ScrollController();
  void _scrollToend() {
    scrollController.jumpTo(scrollController.position.maxScrollExtent);
  }

  late Timer _timer;
  var state = false;
  int selected = 1;
  // ignore: constant_identifier_names
  static const option_int = [3, 5, 7, 10];
  static const option = ["3", "5", "7", "10"];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SafeArea(
          minimum: const EdgeInsets.symmetric(horizontal: 5),
          child: SingleChildScrollView(
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            brokenLine(context, DataNode, scrollController),
            const Divider(),
            Center(
                child: ElevatedButton(
                    onPressed: () async {
                      if (await dev.get() == false) {
                        BrnToast.show('获取失败，请检查节点和网络！', context);
                      }
                      _scrollToend();
                      setState(() {
                        DataNode;
                      });
                    },
                    child: const Text('清除数据并获取数据'))),
            const SizedBox(height: 16),

            /// 输入框
            Center(
              child: ElevatedButton(
                  onPressed: () {
                    if (state) {
                      ScaffoldMessenger.of(context).clearSnackBars();
                      _timer.cancel();
                      setState(() {
                        state = !state;
                      });
                    }

                    /// 弹出表单
                    showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) => StatefulBuilder(// 嵌套一个StatefulBuilder 部件
                                builder: (context, setState) {
                              return SizedBox(
                                height: MediaQuery.of(context).size.height,
                                width: MediaQuery.of(context).size.width,
                                child: ListView(children: [
                                  BrnCommonCardTitle(
                                    title: '设备信息',
                                    detailTextString: '点击对应项修改信息',
                                    detailColor: Colors.grey,
                                    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                                  ),
                                  const Divider(),
                                  ListTile(
                                      title: const Text('设备ID'),
                                      subtitle: Text(dev.device_id),
                                      onTap: () {
                                        BrnMiddleInputDialog(
                                            title: '设备ID',
                                            hintText: '设备ID',
                                            cancelText: '取消',
                                            confirmText: '确定',
                                            autoFocus: true,
                                            inputFormatters: [
                                              FilteringTextInputFormatter.digitsOnly,
                                              LengthLimitingTextInputFormatter(9)
                                            ],
                                            barrierDismissible: true,
                                            onConfirm: (value) {
                                              BrnToast.show(value, context);
                                              Navigator.pop(context);
                                              setState(() {
                                                dev.device_id = value;
                                              });
                                            },
                                            onCancel: () {
                                              Navigator.pop(context);
                                            }).show(context);
                                      }),
                                  const Divider(),
                                  ListTile(
                                      title: const Text('APIKey'),
                                      subtitle: Text(dev.api_key),
                                      onTap: () {
                                        BrnMiddleInputDialog(
                                            title: 'APIKey',
                                            hintText: 'APIKey',
                                            cancelText: '取消',
                                            confirmText: '确定',
                                            autoFocus: true,
                                            maxLength: 100,
                                            barrierDismissible: true,
                                            onConfirm: (value) {
                                              BrnToast.show(value, context);
                                              Navigator.pop(context);
                                              setState(() {
                                                dev.api_key = value;
                                              });
                                            },
                                            onCancel: () {
                                              Navigator.pop(context);
                                            }).show(context);
                                      }),
                                  const Divider(),
                                  ListTile(
                                      title: const Text('数据模板'),
                                      subtitle: Text(dev.dsid),
                                      onTap: () {
                                        BrnMiddleInputDialog(
                                            title: '数据模板',
                                            hintText: '数据ID',
                                            cancelText: '取消',
                                            confirmText: '确定',
                                            autoFocus: true,
                                            maxLength: 100,
                                            inputEditingController: TextEditingController()..text = dev.dsid,
                                            barrierDismissible: true,
                                            onConfirm: (value) {
                                              Navigator.pop(context);
                                              setState(() {
                                                dev.dsid = value;
                                              });
                                            },
                                            onCancel: () {
                                              Navigator.pop(context);
                                            }).show(context);
                                      }),
                                  const Divider(),
                                  ListTile(
                                      title: const Text('数据刷新频率'),
                                      subtitle: Text(option[selected]),
                                      onTap: () async {
                                        await showDialog(
                                          context: context,
                                          builder: (_) => StatefulBuilder(builder: (context, state) {
                                            return BrnSingleSelectDialog(
                                                title: '数据刷新频率(单位：s)',
                                                conditions: option,
                                                checkedItem: option[selected],
                                                submitText: '确认',
                                                submitBgColor: Colors.green,
                                                onItemClick: (BuildContext context, int index) {
                                                  selected = index;
                                                  state(() {});
                                                },
                                                onSubmitClick: (data) {});
                                          }),
                                        );
                                        setState(() {});
                                      }),
                                  const Divider(),
                                ]),
                              );
                            }));
                  },
                  child: const Text("更改节点")),
            ),
          ]))),
      floatingActionButtonLocation: FloatingActionButtonLocation.miniCenterFloat,
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // await dev.get(DSID);
          if (state == true) {
            ScaffoldMessenger.of(context).clearSnackBars();
            _timer.cancel();
          } else {
            const snackBar = SnackBar(
              content: Text('实时读取中', textAlign: TextAlign.center),
              backgroundColor: Colors.green,
              duration: Duration(seconds: 1000000),
            );
            ScaffoldMessenger.of(context).showSnackBar(snackBar);

            /// 自动获取数据
            _timer = Timer.periodic(Duration(seconds: option_int[selected]), (timer) {
              dev.real_update();
              setState(() {});
              _scrollToend();
            });
          }

          setState(() {
            state = !state;
          });
        },
        tooltip: '实时读取',
        child: state ? const Icon(Icons.stop_circle) : const Icon(Icons.play_circle),
      ),
    );
  }
}
